// pages/product/product.js
const result = require('../../utils/requst.js');
const util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: 0,
    active: 0,
    foods: [],
    tabList: [],
    everyFood: {},
    newEveryFood: [],
    count: [],
    goodsList:[]//添加的商品存储
  },
  //侧边栏的tab切换
  async getmsqdata(){
     let res =await result.setData('produce/list?page=0')
      //侧边栏的后台数据
     let res2=await result.setData('foodsname/name?name=1')
     this.setData({
       everyFood:res.data.datas,
       tabList: res2.data.datas
     })
     this.handelerGetList()
  },
  async handelerGetList(e) {
      const foods=this.data.everyFood
        let list = []
        foods.map(d => {
          list.push({
            id: d.id,
            value: 0
          })
        })
        this.setData({
          count: list
        })
          // 默认显示第一个页面
          const {everyFood}=this.data
          if (!e) {
            this.setData({
              foods: everyFood.filter(d => d.biaoji == 0)
            })
          } else {
            this.setData({
              foods: everyFood.filter(d => d.biaoji == e.target.dataset.index),
              active: e.target.dataset.index
            })
          }    
      },
  // 点击物品跳转到相应的详情页面
  handelerGetfood(e) {
    let data = this.data.foods[e.currentTarget.dataset.index]
    wx.navigateTo({
      url: '/pages/details/details',
      success: function (res) {
        res.eventChannel.emit("aaa", {
          data: data
        })
      }
    })
  },
  addfood(e) {
    let {everyFood} = this.data
    let list = [...this.data.goodsList]
   let bb = util.compute(everyFood,e.target.dataset.i)
    everyFood[bb].num++
    
    let index = list.findIndex(d=>d.id == everyFood[bb].id)
    if(index>-1){
      list[index] = everyFood[bb]
    }else{
      list.push(everyFood[bb])
    }
    

    this.setData({
      everyFood:everyFood,
      goodsList:list
    },()=>{
      if(util.storage.get('goodsList')){
        util.storage.remove('goodList')
      }
      util.storage.set('goodsList',list)
    })
    this.handelerGetList()

  },
  delfood(e){
    let {everyFood} = this.data
    let bb = util.compute(everyFood,e.target.dataset.ii)
    if(everyFood[bb].num>0){
      everyFood[bb].num--
    }else{
      everyFood[bb].num=0
    }
    this.setData({
      everyFood:everyFood
    })
    this.handelerGetList()
  },
   handelerPassData(){
      
   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getmsqdata()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})